/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package trivia.gui;

import javax.microedition.lcdui.*;

import trivia.Subject;
import trivia.Test;
import trivia.TriviaMIDlet;

/**
 *
 * @author mourawi
 */
public class TestController implements CommandListener {

    private Subject subject;

    private Test test;

    private TriviaMIDlet midLet;

    private ProblemForm problemForm;

    private ResultsForm resultsForm;

    
    public TestController(TriviaMIDlet midLet) {
        this.midLet = midLet;

        problemForm = new ProblemForm();
        problemForm.setCommandListener(this);

        resultsForm = new ResultsForm();
        resultsForm.setCommandListener(this);
    }


    public void start(Subject subject) {
        this.subject = subject;
        test = new Test(subject);

        problemForm.setSubject(subject);
        problemForm.displayProblem(test.getActiveProblemIndex(),test.getActiveProblem());
        midLet.switchDisplayable(null,problemForm);
    }

    
    public void commandAction(Command command, Displayable displayable) {
        if(displayable == problemForm) {
            if(command.getCommandType() == Command.OK) {
                test.processUserAnswer(problemForm.getUserAnswer());
                if(test.hasNextProblem()) {
                    test.takeNextProblem();
                    problemForm.displayProblem(test.getActiveProblemIndex(),test.getActiveProblem());
                } else {
                    resultsForm.displayResults(test);
                    midLet.switchDisplayable(null,resultsForm);
                }
            } else if(command.getCommandType() == Command.CANCEL) {
                midLet.startOver();
            }
        } else  if(displayable == resultsForm) {
            if(command.getCommandType() == Command.OK) {
                midLet.startOver();
            } else if(command.getCommandType() == Command.BACK) {
                start(subject);
            }
        }
    }

}
